'use client'
import React, { useState, useEffect, use } from "react";
import dynamic from "next/dynamic";
import PageTitle from "@/components/admin/common/PageTitle";
import message from "@/components/common/message";
import Loading from "@/components/common/Loading";

const JsonEditorClient = dynamic(() => import("@/components/admin/common/JsonEditorClient"), { ssr: false });

export default function Page() {
  const [json, setJson] = useState({});
  const [originJson, setOriginJson] = useState({});
  const [isLoaded, setIsLoaded] = useState(false);
  const [isChanged, setIsChanged] = useState(false);

  const jsonChangeEvent = (updatedJson) => {
    setJson(updatedJson);
  };

  const handleReset = () => {
    setJson(originJson);
  };

  useEffect(() => {
    const isChanged = JSON.stringify(json) !== JSON.stringify(originJson);
    setIsChanged(isChanged);
  }, [json, originJson])

  useEffect(() => {
    fetch('/api/admin/json', { method: 'GET' })
      .then(response => response.json())
      .then(data => {
        if (data.code === 0) {
          setJson(data.data);
          setOriginJson(data.data);
          setIsLoaded(true);
        } else {
          message.error(data.codeMap[data.code]||'加载失败');
        }
      })
  }, []);

  const saveEvent = () => {
    fetch('/api/admin/json', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(json) })
    .then(response => response.json())
      .then(data => {
        if (data.code === 0) {
          message.success(data.codeMap[data.code]||'保存成功');
          setOriginJson(json);
        } else {
          message.error(data.codeMap[data.code]||'保存失败');
        }
      })
  }

  return (
    <>
      {
        isLoaded ? <div>
          <PageTitle title="JSON配置" buttonText="Save" onButtonClick={saveEvent} buttonDisabled={!isChanged} extraButtonText={isChanged ? "Reset" : ''} onExtraButtonClick={handleReset}/>
          <JsonEditorClient json={json} onJsonChange={jsonChangeEvent} />
        </div> :
          <Loading />
      }
    </>
  );
}